import React, { useState, useCallback, useEffect } from 'react';
import { Table, Input, Button, Space, Select, DatePicker, Form } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { debounce } from '../utils';

const { RangePicker } = DatePicker;
const { Option } = Select;

/**
 * 搜索表格组件
 * 提供统一的搜索和表格展示功能
 */
const SearchTable = ({
  columns,
  dataSource,
  loading,
  pagination,
  onSearch,
  onReset,
  searchFields = [],
  extraActions = [],
  rowKey = 'id',
  ...tableProps
}) => {
  const [form] = Form.useForm();
  const [searchLoading, setSearchLoading] = useState(false);

  // 防抖搜索
  const debouncedSearch = useCallback(
    debounce((values) => {
      setSearchLoading(true);
      onSearch?.(values).finally(() => setSearchLoading(false));
    }, 500),
    [onSearch]
  );

  // 重置搜索
  const handleReset = useCallback(() => {
    form.resetFields();
    onReset?.();
  }, [form, onReset]);

  // 处理搜索
  const handleSearch = useCallback((values) => {
    debouncedSearch(values);
  }, [debouncedSearch]);

  // 渲染搜索字段
  const renderSearchField = (field) => {
    switch (field.type) {
      case 'input':
        return (
          <Input
            placeholder={field.placeholder || '请输入'}
            allowClear
            {...field.props}
          />
        );
      
      case 'select':
        return (
          <Select
            placeholder={field.placeholder || '请选择'}
            allowClear
            {...field.props}
          >
            {field.options?.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );
      
      case 'date':
        return (
          <RangePicker
            showTime={field.showTime}
            format={field.format || 'YYYY-MM-DD'}
            {...field.props}
          />
        );
      
      case 'custom':
        return field.render?.(form);
      
      default:
        return null;
    }
  };

  return (
    <div>
      {/* 搜索表单 */}
      {searchFields.length > 0 && (
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          initialValues={tableProps.initialValues}
          style={{ marginBottom: 16 }}
        >
          <Space size="middle" wrap>
            {searchFields.map(field => (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
                rules={field.rules}
              >
                {renderSearchField(field)}
              </Form.Item>
            ))}
            
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={searchLoading}
                  icon={<SearchOutlined />}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} icon={<ReloadOutlined />}>
                  重置
                </Button>
                {extraActions}
              </Space>
            </Form.Item>
          </Space>
        </Form>
      )}

      {/* 数据表格 */}
      <Table
        columns={columns}
        dataSource={dataSource}
        loading={loading || searchLoading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          ...pagination,
        }}
        rowKey={rowKey}
        {...tableProps}
      />
    </div>
  );
};

export default SearchTable;